package com.example.seabedmusic.adapter;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.seabedmusic.R;
import com.example.seabedmusic.entity.Song;
import com.example.seabedmusic.utils.LocalMusicManager;
import com.example.seabedmusic.utils.PlaylistManager;

import java.util.ArrayList;
import java.util.List;

public class WoDeAdapter extends RecyclerView.Adapter<WoDeAdapter.VH> {
    private final List<Song> list;
    private OnSongClickListener onSongClickListener;
    private boolean showMoreOptions = true; // 控制是否显示更多选项
    private boolean isLocalMusic = false; // 新增：是否为本地音乐页面
    private boolean isPlaylistDetail = false; // 新增：是否为歌单详情页面
    private String currentPlaylistId; // 新增：当前歌单ID

    // 歌曲点击监听接口
    public interface OnSongClickListener {
        void onSongClick(Song song);
        void onMoreClick(Song song);
    }

    public WoDeAdapter(List<Song> list) {
        this.list = list;
    }

    /**
     * 设置是否显示更多选项
     */
    public void setShowMoreOptions(boolean show) {
        this.showMoreOptions = show;
        notifyDataSetChanged();
    }

    /**
     * 设置是否为本地音乐页面
     */
    public void setIsLocalMusic(boolean isLocalMusic) {
        this.isLocalMusic = isLocalMusic;
        notifyDataSetChanged();
    }

    /**
     * 设置是否为歌单详情页面
     */
    public void setIsPlaylistDetail(boolean isPlaylistDetail, String playlistId) {
        this.isPlaylistDetail = isPlaylistDetail;
        this.currentPlaylistId = playlistId;
        notifyDataSetChanged();
    }

    /**
     * 设置歌曲点击监听器
     */
    public void setOnSongClickListener(OnSongClickListener listener) {
        this.onSongClickListener = listener;
    }

    /**
     * 更新数据
     */
    public void updateData(List<Song> newList) {
        list.clear();
        list.addAll(newList);
        notifyDataSetChanged();
    }

    /**
     * 获取指定位置的歌曲
     */
    public Song getSongAtPosition(int position) {
        if (position >= 0 && position < list.size()) {
            return list.get(position);
        }
        return null;
    }

    static class VH extends RecyclerView.ViewHolder {
        TextView tvTitle, tvArtist;
        ImageView ivCover, ivMore;

        VH(View v) {
            super(v);
            tvTitle = v.findViewById(R.id.tvTitle);
            tvArtist = v.findViewById(R.id.tvArtist);
            ivCover = v.findViewById(R.id.ivMusicIcon);
            ivMore = v.findViewById(R.id.ivMore);
        }
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup p, int viewType) {
        View v = LayoutInflater.from(p.getContext())
                .inflate(R.layout.wode_item_music, p, false);
        return new VH(v);
    }

    @Override
    public void onBindViewHolder(@NonNull VH h, int position) {
        Song s = list.get(position);
        h.tvTitle.setText(s.getTitle());
        h.tvArtist.setText(s.getArtist());

        // 加载歌曲封面图片
        loadSongCover(h.ivCover, s);

        // 设置更多按钮可见性
        h.ivMore.setVisibility(showMoreOptions ? View.VISIBLE : View.GONE);

        // 设置整个item的点击事件
        h.itemView.setOnClickListener(v -> {
            if (onSongClickListener != null) {
                onSongClickListener.onSongClick(s);
            }
        });

        // 设置更多按钮点击事件 - 修复：统一处理
        h.ivMore.setOnClickListener(v -> {
            // 直接显示更多选项对话框
            showMoreOptionsDialog(v.getContext(), s);

            // 同时通知外部监听器（用于日志记录等）
            if (onSongClickListener != null) {
                onSongClickListener.onMoreClick(s);
            }
        });
    }

    /**
     * 显示更多选项对话框（内置实现）
     */
    private void showMoreOptionsDialog(android.content.Context context, Song song) {
        String[] options;

        if (isLocalMusic) {
            // 本地音乐的选项
            options = new String[]{
                    "添加到我喜欢",
                    "从本地音乐移除",
                    "添加到歌单",
                    "分享",
                    "取消"
            };
        } else if (isPlaylistDetail) {
            // 歌单详情页面的选项
            options = new String[]{
                    "添加到我喜欢",
                    "添加到其他歌单",
                    "从歌单移除",
                    "分享",
                    "查看详情",
                    "取消"
            };
        } else {
            // 最近播放的选项
            options = new String[]{
                    "添加到我喜欢",
                    "添加到歌单",
                    "分享",
                    "查看详情",
                    "下载到本地",
                    "取消"
            };
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(song.getTitle());
        builder.setItems(options, (dialog, which) -> {
            handleOptionSelection(context, song, which, options);
        });
        builder.show();
    }

    /**
     * 处理选项选择
     */
    private void handleOptionSelection(android.content.Context context, Song song, int which, String[] options) {
        // 检查是否是取消选项
        if (which == options.length - 1 && "取消".equals(options[which])) {
            return; // 取消选项，不做任何操作
        }

        if (isLocalMusic) {
            // 本地音乐的选项处理
            switch (which) {
                case 0: // 添加到我喜欢
                    addToFavorite(context, song);
                    break;
                case 1: // 从本地音乐移除
                    removeFromLocalMusic(context, song);
                    break;
                case 2: // 添加到歌单
                    addToPlaylist(context, song);
                    break;
                case 3: // 分享
                    shareSong(context, song);
                    break;
            }
        } else if (isPlaylistDetail) {
            // 歌单详情页面的选项处理
            switch (which) {
                case 0: // 添加到我喜欢
                    addToFavorite(context, song);
                    break;
                case 1: // 添加到其他歌单
                    addToOtherPlaylist(context, song);
                    break;
                case 2: // 从歌单移除
                    removeFromPlaylist(context, song);
                    break;
                case 3: // 分享
                    shareSong(context, song);
                    break;
                case 4: // 查看详情
                    showSongDetails(context, song);
                    break;
            }
        } else {
            // 最近播放的选项处理
            switch (which) {
                case 0: // 添加到我喜欢
                    addToFavorite(context, song);
                    break;
                case 1: // 添加到歌单
                    addToPlaylist(context, song);
                    break;
                case 2: // 分享
                    shareSong(context, song);
                    break;
                case 3: // 查看详情
                    showSongDetails(context, song);
                    break;
                case 4: // 下载到本地
                    downloadToLocalMusic(context, song);
                    break;
            }
        }
    }

    /**
     * 添加到我喜欢
     */
    private void addToFavorite(android.content.Context context, Song song) {
        PlaylistManager playlistManager = PlaylistManager.getInstance();
        boolean success = playlistManager.addToFavorite(song);

        if (success) {
            Toast.makeText(context, "已添加到我喜欢", Toast.LENGTH_SHORT).show();
            // 更新歌曲的喜欢状态
            song.setFavorite(true);
        } else {
            Toast.makeText(context, "已在我喜欢中", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 从本地音乐移除
     */
    private void removeFromLocalMusic(android.content.Context context, Song song) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("确认移除");
        builder.setMessage("确定要从本地音乐移除《" + song.getTitle() + "》吗？");
        builder.setPositiveButton("确定", (dialog, which) -> {
            LocalMusicManager localMusicManager = LocalMusicManager.getInstance(context);
            boolean success = localMusicManager.removeSongFromLocal(song);

            if (success) {
                Toast.makeText(context, "已从本地音乐移除", Toast.LENGTH_SHORT).show();
                // 从列表中移除
                int position = list.indexOf(song);
                if (position != -1) {
                    list.remove(position);
                    notifyItemRemoved(position);
                }
            } else {
                Toast.makeText(context, "移除失败", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 从歌单移除歌曲
     */
    private void removeFromPlaylist(android.content.Context context, Song song) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("确认移除");
        builder.setMessage("确定要从歌单中移除《" + song.getTitle() + "》吗？");
        builder.setPositiveButton("确定", (dialog, which) -> {
            PlaylistManager playlistManager = PlaylistManager.getInstance();
            boolean success = playlistManager.removeSongFromPlaylist(currentPlaylistId, song);

            if (success) {
                Toast.makeText(context, "已从歌单移除", Toast.LENGTH_SHORT).show();
                // 从列表中移除
                int position = list.indexOf(song);
                if (position != -1) {
                    list.remove(position);
                    notifyItemRemoved(position);
                }
            } else {
                Toast.makeText(context, "移除失败", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 添加到其他歌单
     */
    private void addToOtherPlaylist(android.content.Context context, Song song) {
        PlaylistManager playlistManager = PlaylistManager.getInstance();

        // 获取所有歌单（排除当前歌单和"我喜欢的"）
        List<com.example.seabedmusic.entity.Playlist> playlists = playlistManager.getAllPlaylists();
        List<com.example.seabedmusic.entity.Playlist> availablePlaylists = new ArrayList<>();

        for (com.example.seabedmusic.entity.Playlist playlist : playlists) {
            if (!"我喜欢的".equals(playlist.getName()) && !playlist.getId().equals(currentPlaylistId)) {
                availablePlaylists.add(playlist);
            }
        }

        if (availablePlaylists.isEmpty()) {
            Toast.makeText(context, "没有其他可用歌单", Toast.LENGTH_SHORT).show();
            return;
        }

        String[] playlistNames = new String[availablePlaylists.size()];
        for (int i = 0; i < availablePlaylists.size(); i++) {
            playlistNames[i] = availablePlaylists.get(i).getName() + " (" + availablePlaylists.get(i).getSongCount() + "首)";
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("选择歌单");
        builder.setItems(playlistNames, (dialog, which) -> {
            com.example.seabedmusic.entity.Playlist selectedPlaylist = availablePlaylists.get(which);
            boolean success = playlistManager.addSongToPlaylist(selectedPlaylist.getId(), song);

            if (success) {
                Toast.makeText(context, "已添加到歌单: " + selectedPlaylist.getName(), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "歌曲已在歌单中", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 下载到本地音乐
     */
    private void downloadToLocalMusic(android.content.Context context, Song song) {
        LocalMusicManager localMusicManager = LocalMusicManager.getInstance(context);
        boolean success = localMusicManager.addSongToLocal(song);

        if (success) {
            Toast.makeText(context, "已下载到本地音乐", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, "歌曲已在本地音乐中", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 添加到歌单
     */
    private void addToPlaylist(android.content.Context context, Song song) {
        PlaylistManager playlistManager = PlaylistManager.getInstance();

        // 获取所有歌单（排除"我喜欢的"）
        List<com.example.seabedmusic.entity.Playlist> playlists = playlistManager.getAllPlaylists();
        List<com.example.seabedmusic.entity.Playlist> userPlaylists = new ArrayList<>();

        for (com.example.seabedmusic.entity.Playlist playlist : playlists) {
            if (!"我喜欢的".equals(playlist.getName())) {
                userPlaylists.add(playlist);
            }
        }

        if (userPlaylists.isEmpty()) {
            Toast.makeText(context, "请先创建歌单", Toast.LENGTH_SHORT).show();
            return;
        }

        String[] playlistNames = new String[userPlaylists.size()];
        for (int i = 0; i < userPlaylists.size(); i++) {
            playlistNames[i] = userPlaylists.get(i).getName() + " (" + userPlaylists.get(i).getSongCount() + "首)";
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("添加到歌单");
        builder.setItems(playlistNames, (dialog, which) -> {
            com.example.seabedmusic.entity.Playlist selectedPlaylist = userPlaylists.get(which);
            boolean success = playlistManager.addSongToPlaylist(selectedPlaylist.getId(), song);

            if (success) {
                Toast.makeText(context, "已添加到歌单: " + selectedPlaylist.getName(), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "歌曲已在歌单中", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 分享歌曲
     */
    private void shareSong(android.content.Context context, Song song) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        String shareText = "分享歌曲: " + song.getTitle() + " - " + song.getArtist();
        if (song.getAlbum() != null && !song.getAlbum().isEmpty()) {
            shareText += " (专辑: " + song.getAlbum() + ")";
        }
        shareIntent.putExtra(Intent.EXTRA_TEXT, shareText);
        context.startActivity(Intent.createChooser(shareIntent, "分享歌曲"));
    }

    /**
     * 显示歌曲详情
     */
    private void showSongDetails(android.content.Context context, Song song) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("歌曲详情");

        PlaylistManager playlistManager = PlaylistManager.getInstance();
        LocalMusicManager localMusicManager = LocalMusicManager.getInstance(context);

        String details = "歌曲: " + song.getTitle() + "\n" +
                "歌手: " + song.getArtist() + "\n" +
                "专辑: " + (song.getAlbum() != null ? song.getAlbum() : "未知") + "\n" +
                "时长: " + formatDuration(song.getDuration()) + "\n" +
                "是否喜欢: " + (playlistManager.isFavorite(song) ? "是" : "否") + "\n" +
                "是否本地: " + (song.isLocal() || localMusicManager.isSongInLocal(song) ? "是" : "否");

        builder.setMessage(details);
        builder.setPositiveButton("确定", null);
        builder.show();
    }

    /**
     * 格式化时长
     */
    private String formatDuration(long duration) {
        if (duration <= 0) return "未知";

        long minutes = duration / 60000;
        long seconds = (duration % 60000) / 1000;
        return String.format("%d:%02d", minutes, seconds);
    }

    /**
     * 加载歌曲封面图片
     */
    private void loadSongCover(ImageView imageView, Song song) {
        String coverUrl = song.getCover();

        // 创建圆角变换
        RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.drawable.ic_music_note)
                .error(R.drawable.ic_music_note)
                .transform(new RoundedCorners(dpToPx(imageView.getContext(), 8)));

        if (coverUrl != null && !coverUrl.trim().isEmpty() && !coverUrl.equals("null")) {
            // 使用Glide加载网络图片
            Glide.with(imageView.getContext())
                    .load(coverUrl)
                    .apply(requestOptions)
                    .into(imageView);
        } else {
            // 如果没有封面URL，显示默认图标
            Glide.with(imageView.getContext())
                    .load(R.drawable.ic_music_note)
                    .apply(requestOptions)
                    .into(imageView);
        }
    }

    /**
     * dp转px
     */
    private int dpToPx(android.content.Context context, float dp) {
        float density = context.getResources().getDisplayMetrics().density;
        return Math.round(dp * density);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
}